<template>
  <div class="login-container" :style="style">
    <div class="h-full flex md:flex-row-reverse">
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        autocomplete="on"
        label-position="left"
      >
        <div class="title-container">
          <div v-if="showLoginLogo" class="text-center mt-5 mb-5">
            <img
              class="inline-block h-20"
              src="/logo.png"
              :alt="$t('login.title', { title })"
            />
          </div>
          <h3 class="title" v-t="{ path: 'login.title', args: { title } }"></h3>
        </div>

        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon name="user" />
          </span>
          <el-input
            ref="username"
            v-model="loginForm.username"
            :placeholder="$t('login.username')"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
          <!-- style="font-size:25px;margin-left:25px;margin-bottom:-5px;" -->
        </el-form-item>

        <el-tooltip
          v-model="capsTooltip"
          content="Caps lock is On"
          placement="right"
          manual
        >
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon name="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              :placeholder="$t('login.password')"
              name="password"
              tabindex="2"
              autocomplete="on"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleLogin"
            />
            <!-- style="font-size:25px;margin-left:25px;" -->
            <span class="show-pwd" @click="showPwd">
              <svg-icon
                :name="passwordType === 'password' ? 'eye-off' : 'eye-on'"
              />
            </span>
          </el-form-item>
        </el-tooltip>

        <el-button
          :loading="loading"
          type="darkOrange"
          class="login-btn"
          @click.native.prevent="handleLogin"
        >
          <span style="font-size: 22px">
            {{ $t('login.logIn') }}
          </span>
        </el-button>

        <div v-if="enableRegister" style="position: relative">
          <div class="tips">
            <el-link type="info" href="http://www.mimaosou.com" target="_blank">
              <span style="font-size: 16px">{{ $t('login.register') }}</span>
            </el-link>
          </div>
        </div>

        <!--&lt;!&ndash;        <el-button&ndash;&gt;-->
        <!--&lt;!&ndash;          class="thirdparty-button"&ndash;&gt;-->
        <!--&lt;!&ndash;          type="primary"&ndash;&gt;-->
        <!--&lt;!&ndash;          @click="showDialog=true"&ndash;&gt;-->
        <!--&lt;!&ndash;        >&ndash;&gt;-->
        <!--&lt;!&ndash;          {{ $t('login.thirdparty') }}&ndash;&gt;-->
        <!--&lt;!&ndash;        </el-button>&ndash;&gt;-->
        <!--      </div>-->
      </el-form>
    </div>
    <el-dialog :title="$t('login.thirdparty')" :visible.sync="showDialog">
      {{ $t('login.thirdpartyTips') }}
      <br />
      <br />
      <br />
      <social-sign />
    </el-dialog>
  </div>
</template>

<script>
import { UserModule } from '@/store/modules/user'
import { isValidUsername } from '@/utils/validate'
import SocialSign from './components/SocialSignin.vue'
import { OemModule } from '@/store/modules/oem'

export default {
  name: 'Login',
  components: {
    SocialSign,
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!isValidUsername(value)) {
        callback(new Error(this.$t('login.username')))
      } else {
        callback()
      }
    }

    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error(this.$t('login.password')))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
      },
      loginRules: {
        username: [{ validator: validateUsername, trigger: 'blur' }],
        password: [{ validator: validatePassword, trigger: 'blur' }],
      },

      passwordType: 'password',
      loading: false,
      showDialog: false,
      capsTooltip: false,
      redirect: undefined,
      otherQuery: {},
      style: {},
    }
  },
  created() {
    if (OemModule.id === 9)
      this.style = {
        backgroundImage: 'url(/img/login_bg_dashi.jpg)',
      }
  },
  watch: {
    $route: {
      immediate: true,
      handler: function (route) {
        // TODO: remove the "as Dictionary<string>" hack after v4 release for vue-router
        // See https://github.com/vuejs/vue-router/pull/2050 for details
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)

          console.log(query.redirect)
          console.log(this.getOtherQuery(query))
        }
      },
    },
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  computed: {
    title() {
      return OemModule.name
    },
    showLoginLogo() {
      return OemModule.showLoginLogo
    },
    enableRegister() {
      return location.host === 'crm.yimisoft.com'
    },
  },
  methods: {
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip =
        key !== null && key.length === 1 && key >= 'A' && key <= 'Z'
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          UserModule.Login(this.loginForm)
            .then(() => {
              this.$router
                .push({
                  path: this.redirect || '/',
                  query: this.otherQuery,
                })
                .catch((err) => {
                  console.warn(err)
                })
            })
            .finally(() => {
              // Just to simulate the time of the request
              setTimeout(() => {
                this.loading = false
              }, 0.5 * 1000)
            })
        } else {
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
  },
}
</script>

<style lang="scss" scoped>
// References: https://www.zhangxinxu.com/wordpress/2018/01/css-caret-color-first-line/
@supports (-webkit-mask: none) and (not (cater-color: $loginCursorColor)) {
  .login-container .el-input {
    input {
      color: $loginCursorColor;
    }
    input::first-line {
      color: $lightGray;
    }
  }
}

.login-container {
  &::v-deep .el-input {
    display: inline-block;
    height: 50px;
    width: 85%;
    font-size: 25px;
    margin-left: 25px;

    input {
      height: 50px;
      line-height: 50px;
      background: transparent;
      border: 0px;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $darkGray;
      caret-color: $darkGray;
      -webkit-appearance: none;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $loginBg inset !important;
        -webkit-text-fill-color: #fff !important;
      }
      &::first-line {
        color: #666666;
      }
    }
  }

  &::v-deep .el-form-item__error {
    font-size: 18px;
  }

  .el-form-item {
    border: 1px solid #889aa4;
    //background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #666666;
    margin-bottom: 31px;
  }

  .login-btn {
    width: 458px;
    height: 50px;
    margin-top: 10px;
    border-radius: 30px;
  }
}

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
// .el-select .el-input {
//   width: 458px;
//   height: 55px;
// }
.login-container {
  height: 100%;
  width: 100%;
  overflow: hidden;
  // background-color: $darkOrange;
  background-color: black;
  background: url('~@/assets/login_bg.jpeg');
  background-size: cover;

  .login-form {
    @apply bg-white rounded-[20px] p-7.5 m-auto mt-45 md:mx-0 md:mr-30;
  }

  .tips {
    font-size: 25px;
    color: #fff;
    margin: 20px 0px 10px;
    text-align: center;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding-left: 15px;
    color: #666666;
    // vertical-align: middle;
    width: 30px;
    font-size: 26px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    color: #424242;
    .title {
      font-size: 22px;
      margin: 0px auto 30px auto;
      color: #333333;
      text-align: center;
      font-weight: unset;
    }

    .sub-title {
      color: #4a4a4a;
      text-align: center;
    }

    .set-language {
      color: #fff;
      position: absolute;
      top: 3px;
      font-size: 18px;
      right: 0px;
      cursor: pointer;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $darkGray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
